#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include "myjni.h"
#include "platform_config.h"


int GPS_POINT_Index1 = 0;
double LengMaxx;
double LengMaxy;
double currentLatitude = 0;
double currentLongitude = 0;
int CaliAreaFlag = 1;//为0实时连续计算面积，为1最终面积计算
int AddPointFlag = 0;//为0不加点，为1加点
double BottomMaxy;
double g_tminx;
double g_tminy;
double g_tmaxx;
double g_tmaxy;
u16 g_workSeconds = 0;
u32  g_pesticidesLiter = 0;//农药消耗量
u32  g_PercentOfAreaPassed = 0;//亩数合格率
static u32 planePointIndex = 0;
double MeterInPerLat = 0;//每1纬度变化，代表多少米
double MeterInperLng = 0;//每1经度变化，代表多少米
stru_GPSPOINT   planePoint[MAX_GPS_POINT];
stru_GPSPOINT   GPS_POINT_Data2[MAX_OUTLINE_POINT];
stru_GPSPOINT gps_point_ref;
u32  g_pesticidesAdBuff[MAX_GPS_POINT];//农药AD值
stru_GPSPOINT g_middlePoint;
u16  g_recordPointsNumber = 0;
u8 g_flagOfStartWork = 0;
u16 g_startIndex = 0;
u16 g_stopIndex = 0;
static long g_startSeconds = 0;//开始喷药的秒数
static long g_stopSeconds = 0;//结束喷药的秒数
double g_areaInMu = 0;//轮廓面积
double  g_areaOfTravel = 0;//行进面积
double  g_totalDistance = 0;//累计总距离
							//u16  g_workingWidth =500;
static u32 g_gpsPointNum = 0;
static double g_refLatitude = 0;
static double g_refLongitude = 0;
static u8 g_driftingGPSnum = 0;
extern SysInf  SysInfor;
extern u32 g_currentAdValue;
u16 g_emptyCounter = 0;
double g_currentLatitude;
double g_currentLongitude;
unsigned int g_lowestLiquidAdvalue = 4000;
unsigned int g_highestLiquidAdvalue = 0;
unsigned int g_addWaterCounter = 0;//加水计数器
unsigned int g_addWaterEndCounter = 0;
unsigned char g_flagOfAddWater = 0;
unsigned char g_isFinishedOfAddWater = 0;
unsigned char checkIfAddWater(unsigned int adValue);
void clearStateOfAddWater(void);
void autoCalPesticidesLiter(void);
void getlowestAndHighestLiquidAdvalue(unsigned int adValue);
static double CaliAreaXuanDian(void);

static  double roundx(double x) {
	return ((int)(x + 0.5));
}

static double rad(double d) {
	return d * PI / 180.0;
}

/////--------求两点间距离---------/////////////
static double GetDistance(double lat1, double lng1, double lat2, double lng2)
{
	double radLat1 = rad(lat1);
	double radLat2 = rad(lat2);
	double a = radLat1 - radLat2;
	double b = rad(lng1) - rad(lng2);
	double c = 2 * asin(sqrt(pow(sin(a / 2), 2) + cos(radLat1)*cos(radLat2)*pow(sin(b / 2), 2)));

	c = c * EARTH_RADIUS;
	c = roundx(c * 1000000) / 1000;//千米转换为米，取小数点3位
	return c;
}

static double getBearing(double bearing1, double bearing2) {
	double bearing = abs(bearing1 - bearing2);
	if (bearing > 180) {
		bearing = 360 - bearing;
	}
	return bearing;
}

//去除漂移点
u16 removeDriftGpsPoint(double *Latitude, double *Longitude)
{
	double distance = 0;

	if (g_gpsPointNum == 4)//第一个点作为参考点
	{
		g_refLatitude = *Latitude;
		g_refLongitude = *Longitude;
	}
	else if (g_gpsPointNum > 4)
	{
		distance = GetDistance(g_refLatitude, g_refLongitude, *Latitude, *Longitude);
		//时速限定,超限视为漂移点，不更新当前经纬度，连续三次出现坏点时，说明参考点是坏点，剔除参考点，同时更新当前经纬度
		if (distance < MAX_GPS_SPEED_MS * g_driftingGPSnum)
		{
			g_refLatitude = *Latitude;
			g_refLongitude = *Longitude;
			g_driftingGPSnum = 0;
		}
		else //距离超限，视为GPS漂移,去除漂移点
		{
			g_driftingGPSnum++;
			if (g_driftingGPSnum >= 3)//连续3个点都超限时，判定参考点为漂移点
			{
				g_refLatitude = *Latitude;
				g_refLongitude = *Longitude;
			}
			else//当前点为坏点时，不更新当前经纬度
			{
				*Latitude = g_refLatitude;
				*Longitude = g_refLongitude;
			}
			g_gpsPointNum--;
		}
	}
	return distance;

}

//GPS经纬度转换为平面坐标点
void GpsToPlanePoin(double lat, double lng)
{
	//  char temp[20];
	//第一点作为参考点,按键由弹起到按下时，确定参考点

	if (planePointIndex == 0)
	{
		LOGE("gps******参考点: %lf,  %lf", lat, lng);
		gps_point_ref.x = lat;
		gps_point_ref.y = lng;
		MeterInPerLat = GetDistance(lat, lng, lat + 1, lng);
		MeterInperLng = GetDistance(lat, lng, lat, lng + 1);
		memset(planePoint, 0, sizeof(planePoint));
		memset(GPS_POINT_Data2, 0, sizeof(GPS_POINT_Data2));
	}

	//转换坐标系
	planePoint[planePointIndex].x = (lat - gps_point_ref.x)*MeterInPerLat;
	planePoint[planePointIndex].y = (lng - gps_point_ref.y)*MeterInperLng;

}

//记录点信息，包含GPS坐标，响应的药量AD值,定位后，点数超过3个，先执行去除GPS漂移,接收到一个GPS点，执行一次
void recordPointsMessage(double g_currentLatitude, double g_currentLongitude)
{
	u16 i = 0;
	//先进先出，最新的点在队尾
	if (g_recordPointsNumber == MAX_GPS_POINT)
	{
		for (i = 1; i<MAX_GPS_POINT - 1; i++)
		{
			if (pesticidesLiter_button == 1) {
				g_pesticidesAdBuff[i - 1] = g_pesticidesAdBuff[i] | 0x8000;
			}
			else
				g_pesticidesAdBuff[i - 1] = g_pesticidesAdBuff[i];
			planePoint[i - 1].x = planePoint[i].x;
			planePoint[i - 1].y = planePoint[i].y;
		}
	}

	GpsToPlanePoin(g_currentLatitude, g_currentLongitude);//将GPS点转换为平面 坐标，并且保存在缓存中
	if (pesticidesLiter_button == 1) {
		g_pesticidesAdBuff[planePointIndex] = g_currentAdValue | 0x8000;//current4minad;g_currentAdValue//记录当前的液位AD值
	}
	else {
		g_pesticidesAdBuff[planePointIndex] = g_currentAdValue;
	}

	// send_a_num(1,g_pesticidesAdBuff[planePointIndex]);

	if (++planePointIndex >= MAX_GPS_POINT)//缓存边界处理
	{
		planePointIndex = MAX_GPS_POINT - 1;
		g_recordPointsNumber = MAX_GPS_POINT - 1;
	}
	if (g_recordPointsNumber<MAX_GPS_POINT)
		g_recordPointsNumber++;
}

static inline void MEMSET_U16(u16 *src, u16 val, u32 len) {
	u32 i;
	for (i = 0; i < len; i++)
		src[i] = val;
}

long g_secondCounter() {
	struct timeval tv;
	gettimeofday(&tv, NULL);
	return tv.tv_sec;
}
/*
1、不断刷新最高液位和最低液位
2、工作状态下，查看是否有重新加水操作，如果加水，等待加水完毕，清算用药量，备用累计；
3、液位连续升高，即为加水。液位不再升高，即为加水完毕。
*/


//刷新液位的最高值和最低值
void getlowestAndHighestLiquidAdvalue(unsigned int adValue)
{
	//LOGE("查看-----高位-----%d", g_highestLiquidAdvalue);
	//LOGE("查看-----低位-----%d", g_lowestLiquidAdvalue);
	if (g_flagOfAddWater == 0)//加水过程中锁定液位不刷新
	{
		if (adValue > g_highestLiquidAdvalue) {
			g_highestLiquidAdvalue = adValue;
			LOGE("adc******刷新高位-----%d", g_highestLiquidAdvalue);
		}

	}

	if (adValue != 0 && adValue < g_lowestLiquidAdvalue) {//避免通讯中断带来的刷新低位
		g_lowestLiquidAdvalue = adValue;
		LOGE("adc******刷新低位-----%d", g_lowestLiquidAdvalue);
	}
}
unsigned int g_addWaterSeconds = 0;
void autoCalPesticidesLiter(void)
{
	if (++g_addWaterSeconds % 30 == 0)//间隔n次采集周期，比对一次，查看是否有加水
	{
		g_isFinishedOfAddWater = checkIfAddWater(g_currentAdValue);
		if (g_isFinishedOfAddWater == 1) {//加水完毕
			if (g_flagOfStartWork == 1 && g_highestLiquidAdvalue > g_lowestLiquidAdvalue) {//如果之前没有喷洒，说明第一次加水，不用累计之前的用量
				LOGE("adc******清算液位-----高位-----%d", g_highestLiquidAdvalue);
				LOGE("adc******清算液位-----低位-----%d", g_lowestLiquidAdvalue);
				g_pesticidesLiter += calculata_oil(g_highestLiquidAdvalue) - calculata_oil(g_lowestLiquidAdvalue);//工作状态已经开启，结算用药量
				if(g_pesticidesLiter>60000)
				{
				 int work = STOP_WORK;
        		         write(localSocketW, &work, sizeof(work));
				}
				LOGE("adc******累计药量........%u", g_pesticidesLiter);
			}


			clearStateOfAddWater();
		}

	}

}

unsigned int g_adValueOld=0;
unsigned char checkIfAddWater(unsigned int adValue)
{
	if (adValue > 0)//
	{
		if (adValue > (g_adValueOld+ 150))//水量增加
		{
			g_addWaterCounter++;
			
			if (g_addWaterCounter >= 4)//确定有加水
			{
				LOGE("adc******正在加水........");
				g_flagOfAddWater = 1;
			}
			g_addWaterEndCounter = 0;//清除加水停止计数器
		}
		if (adValue < (g_adValueOld+ 100))//水量没有增加
		{
			
			if (++g_addWaterEndCounter >= 4)//n次连续水位不增加，清除加水计数器
			{
				g_addWaterEndCounter = 10;//保持比n大
				g_addWaterCounter = 0;
				if (g_flagOfAddWater == 1)
				{
					LOGE("adc******加水完毕!!!!!!");
					return 1;
				}
			}

		}

		LOGE("adc******addWaterCounter=%d",g_addWaterCounter);	
		LOGE("adc******addWaterEndCounter=%d",g_addWaterEndCounter);
		g_adValueOld = adValue;
	}
	return 0;
}

//清除所有加水状态
void clearStateOfAddWater(void)
{
	//清除所有状态
	g_isFinishedOfAddWater = 0;
	g_addWaterCounter = 0;
	g_flagOfAddWater = 0;
	g_addWaterEndCounter = 0;
	//初始化最低液位和最高液位
	g_highestLiquidAdvalue = 0;
	g_lowestLiquidAdvalue = 4000;
}


void AndroidGpsProcess(double Latitude, double Longitude)
{
	//if (!(work_button || pesticidesLiter_button))//工作按钮或者药箱开关量作为开始条件
	//    return;
	
	if (Latitude < 10.0 || Longitude < 10.0)
		return;

	//刷新液位最高值和最低值
	getlowestAndHighestLiquidAdvalue(g_currentAdValue);
	autoCalPesticidesLiter();//工作状态下，忘记操作按键时，检测到重新加水时，结算之前的喷洒量，备用
	if (g_gpsPointNum < MAX_GPS_POINT)
		g_gpsPointNum++;//gps点数  
	if (g_gpsPointNum > 3)//gps点数超过3个开始记录
	{
		removeDriftGpsPoint(&Latitude, &Longitude);//去除漂移点

		g_currentLatitude = Latitude;
		g_currentLongitude = Longitude;
		LOGE("gps******纬度:%f		经度:%f		方向:%f", Latitude, Longitude, gps_bearing);
		if (pesticidesLiter_button == 1) {//开关量作为喷药的唯一条件
			recordPointsMessage(Latitude, Longitude);  //喷药时，记录每个GPS点的对应信息，及相应的液位
			if (g_flagOfStartWork == 0) {
				g_startIndex = planePointIndex;
				LOGE("adc******开始喷药！！！！！！");
				write_log_to_sdcard("开始喷药！");
				LOGE("g_startIndex==%d", g_startIndex);
				g_areaInMu = 0;
				g_flagOfStartWork = 1;
				g_startSeconds = currentTimeInSec();
			}
		}
	}
}

void stop_work() {
	LOGE("%s", __func__);
	if (g_flagOfStartWork == 0)
		return;
	g_stopIndex = g_recordPointsNumber - 1;
	g_stopSeconds = currentTimeInSec();
	LOGE("adc******$停止喷药##########");
	write_log_to_sdcard("停止喷药！");
	LOGE("gps******g_stopIndex==%d", g_stopIndex);
	CalAreaProcess();
}


//求2个平面坐标点之间的距离
double GetDistanceInPlant(double x1, double y1, double x2, double y2)
{
	double distance = 0;
	distance = fabs(pow((x1 - x2), 2) + pow((y1 - y2), 2));
	return sqrt(distance);
}


//计算行进总距离
void getTotalDistance(void)
{
	u16 i;
	double g_neighborGpsDistances;
	//计算单点移动距
	for (i = g_startIndex; i < g_stopIndex; i++)
	{
		if ((g_pesticidesAdBuff[i] & 0x8000) && (g_pesticidesAdBuff[i + 1] & 0x8000)) {
			g_neighborGpsDistances = GetDistanceInPlant(planePoint[i].x, planePoint[i].y, planePoint[i + 1].x, planePoint[i + 1].y);
			//LOGE("planePoint[i].x:%lf  planePoint[i].y:%lf      线长:%lf", planePoint[i].x, planePoint[i].y, g_neighborGpsDistances);
			//write_log_to_sdcard("planePoint[i].x:%lf  planePoint[i].y:%lf      线长:%lf", planePoint[i].x, planePoint[i].y, g_neighborGpsDistances);
		}
		else {
			g_neighborGpsDistances = 0;
		}
		if (g_neighborGpsDistances < 50)
			g_totalDistance += g_neighborGpsDistances;
	}

}//


 //计算面积
void getAreaOfTravel(void)
{
	g_areaOfTravel = g_totalDistance * SysInfor.WORKING_WIDTH / 66670.0;// * g_workingWidth  / 66670.0;//喷洒宽度的单位是厘米，故而需要除以   (666.7*100)
	LOGE("gps******g_totalDistance = %f", g_totalDistance);
	g_totalDistance = 0;//行进距离清零

}//




 //处理计算作业面积任务
void dealWithWorkingArea(void)
{
	if (planePointIndex >= 10)//超过n个点计算距离
	{
		getTotalDistance();
		getAreaOfTravel();
	}
	else
		g_areaOfTravel = 0;

}//



u32 calculata_oil(u32 adval)
{
	u8 i;
	u32 temp;
	u8 whichSection = 5;
	//返回升数扩大10倍
	for (i = 5; i>0; i--)//查看液位在哪个刻度区间
	{
		if (adval< SysInfor.str_linearList[i - 1].adValue)
		{
			whichSection--;
		}
	}

	if (whichSection == 0)
	{
		if ((short)adval <= SysInfor.EMPTY_AD_VALUE) temp = 0;
		else
		{
			temp = (adval - SysInfor.EMPTY_AD_VALUE) * 10 * SysInfor.str_linearList[0].literOfliquor / (SysInfor.str_linearList[0].adValue - SysInfor.EMPTY_AD_VALUE);
		}
	}
	else if (whichSection == 5)
	{
		temp = SysInfor.str_linearList[whichSection - 1].literOfliquor * 10;
	}
	else
	{
		temp = SysInfor.str_linearList[whichSection - 1].literOfliquor * 10;
		temp += (adval - SysInfor.str_linearList[whichSection - 1].adValue) * 10 *
			(SysInfor.str_linearList[whichSection].literOfliquor - SysInfor.str_linearList[whichSection - 1].literOfliquor) /
			(SysInfor.str_linearList[whichSection].adValue - SysInfor.str_linearList[whichSection - 1].adValue);
	}

	return temp / 10;
}


void removeNonWorkGps(void)
{
	u16 i;
	for (i = 0; i<g_startIndex; i++)
	{
		planePoint[i].x = planePoint[g_startIndex].x;
		planePoint[i].y = planePoint[g_startIndex].y;
	}

}


//求出平面坐标系的最值:最大，最小，中心点
void GetMaxPlanePoint(void)
{
	u16 i;
	double p1x;
	double p1y;
	g_tminx = planePoint[0].x;
	g_tminy = planePoint[0].y;
	g_tmaxx = planePoint[0].x;
	g_tmaxy = planePoint[0].y;
	for (i = 0; i <planePointIndex - 1; i++)//循环所有线条求极值
	{
		p1x = planePoint[i].x;
		p1y = planePoint[i].y;

		if (p1x<g_tminx)g_tminx = p1x;//求最小值
		if (p1y<g_tminy)g_tminy = p1y;

		if (p1x>g_tmaxx)g_tmaxx = p1x;//求最大值
		if (p1y>g_tmaxy)g_tmaxy = p1y;
	}
	LengMaxx = (g_tmaxx - g_tminx);
	LengMaxy = (g_tmaxy - g_tminy);
	g_middlePoint.x = (g_tmaxx + g_tminx) / 2;
	g_middlePoint.y = (g_tmaxy + g_tminy) / 2;
}



//计算亩数合格率
//允许超过100%
u16 CalPercentOfAreaPassed(void)
{
	u16 percent = 0;
	if (g_areaInMu > 0.1 && g_areaOfTravel>0.1)
	{
		percent = g_areaOfTravel * 1000 / g_areaInMu;
	}
	return percent;
}

void CalAreaProcess() //计算面积处理过程
{
	dealWithWorkingArea();//计算行进面积
						  //LOGE("start g_startIndex=%d g_stopIndex=%d", g_startIndex, g_stopIndex);
	LOGE("adc******发送面积前计算液位-----高位-----%d", g_highestLiquidAdvalue);
	LOGE("adc******发送面积前计算液位-----低位-----%d", g_lowestLiquidAdvalue);
	//LOGE("end g_startIndex=%d g_stopIndex=%d", g_startIndex, g_stopIndex);
	if (g_highestLiquidAdvalue > g_lowestLiquidAdvalue)
	{
		//LOGE("开始液位-----%u",calculata_oil( g_pesticidesAdBuff[g_startIndex] & 0x0fff));
		//LOGE("结束液位-----%u",calculata_oil(g_pesticidesAdBuff[g_stopIndex-1] & 0x0fff ));
		g_pesticidesLiter += calculata_oil(g_highestLiquidAdvalue) - calculata_oil(g_lowestLiquidAdvalue);//计算用量,单位0.1L

	}
	else
		g_pesticidesLiter += 0;
	if (g_stopSeconds >= g_startSeconds)
		g_workSeconds = g_stopSeconds - g_startSeconds;//计算用时，单位:秒
	else
		g_workSeconds = g_stopSeconds + 0xffffffff - g_startSeconds;//计算用时，单位:秒

	if (g_isAutoFlag == 1)
	{
		if (g_workSeconds > SysInfor.CALC_AREA_DELAY_SECONDS)
		{
			g_workSeconds = g_workSeconds - ((short)SysInfor.CALC_AREA_DELAY_SECONDS);
		}
		g_isAutoFlag = 0;
	}

	removeNonWorkGps();//将非工作的GPS点用开始位置的GPS点取代，便于后面计算投影面积
	GetMaxPlanePoint();//取出坐标系中最值
	g_areaInMu = CaliAreaXuanDian();//取边界点并计算面积
	g_PercentOfAreaPassed = CalPercentOfAreaPassed();//计算深松面积合格率
													 //print debug message
													 //LOGE("g_areaInMu = %u", (u32)(g_areaInMu*1000));
													 //LOGE("g_areaOfTravel = %u", (u32)(g_areaOfTravel*100));
	LOGE("gps******g_areaInMu = %f", g_areaInMu);
	LOGE("gps******g_areaOfTravel = %f", g_areaOfTravel);
	LOGE("adc******g_pesticidesLiter = %u", g_pesticidesLiter);
	LOGE("gps******g_workSeconds = %u", g_workSeconds);
	//end
	//  if(g_areaInMu>0.1 && g_areaOfTravel>0.1 && g_pesticidesLiter > (g_areaOfTravel*30) )// 1亩地喷药至少0.6升，如果少于0.3升，不上传
	if (g_areaInMu > 0.5 && g_areaOfTravel > 0.5)
	{
		write_gps_info("计算面积数据 面积:%f亩 行进面积:%f亩 药水:%d升 工作时长:%d秒", g_areaInMu, g_areaOfTravel, (u32)g_pesticidesLiter, (u16)g_workSeconds);
		sendAreaData(g_areaInMu * 1000, (u16)(g_areaOfTravel * 100), (u16)g_pesticidesLiter, (u16)g_workSeconds);
	}
	/*if (g_areaInMu < g_areaOfTravel)
	g_led_display = g_areaInMu * 10;
	else
	{
	g_led_display = g_areaOfTravel * 10;
	}*/
	g_led_display = ((unsigned int)(g_areaInMu * 10)) < ((unsigned int)(g_areaOfTravel * 10)) ? (unsigned int)(g_areaInMu * 10) : (unsigned int)(g_areaOfTravel * 10);
	g_led_display_counter = 1;
	calc_area_delay_seconds = -1;   //中断自动的计时器
	g_startIndex = 0;
	g_stopIndex = 0;
	planePointIndex = 0;
	GPS_POINT_Index1 = 0;
	g_flagOfStartWork = 0;
	g_recordPointsNumber = 0;
	g_pesticidesLiter = 0;//发送完后，务必清除用药量
	g_highestLiquidAdvalue = g_currentAdValue;
}

//////////-----多边形求面积-----/////////////
/*static double CaliArea(stru_GPSPOINT pPoint[],int index)//多边形求面积
{
double iArea=0;
u16 i;
for ( i=0; i <index; i++)//循环所有线条
{
iArea += (pPoint[i].x * pPoint[i+1].y) - (pPoint[i+1].x * pPoint[i].y);
}
iArea += (pPoint[index-1].x * pPoint[0].y) - (pPoint[0].x * pPoint[index-1].y);
return iArea=abs(0.5*iArea);
}*/

static double CaliArea(stru_GPSPOINT pPoint[], int index)//多边形求面积
{
	double iArea = 0;
	unsigned short i;
	iArea = pPoint[0].y * (pPoint[index - 1].x - pPoint[1].x);
	for (i = 1; i < index - 1; ++i)
		iArea += pPoint[i].y * (pPoint[i - 1].x - pPoint[i + 1].x);
	return iArea = abs(0.5*iArea);
}

////----求最高连续点-----/////////////
static double TopMiny;
static void CalTopPiont(u32 count)
{
	double ttmaxy = 0;
	double ttmaxx = 0;
	u32 i, j, k;
	double dx;
	k = 0;
	dx = LengMaxx / count;
	for (i = 0; i<count; i++)//分割后循环
	{
		ttmaxy = g_middlePoint.y;
		for (j = 0; j <planePointIndex - 2; j++)//循环所有线条
		{
			if (planePoint[j].x >= (g_tminx + i*dx) && planePoint[j].x <= g_tminx + (i + 1)*dx)
			{
				if (ttmaxy<planePoint[j].y)
				{
					ttmaxy = planePoint[j].y;
					ttmaxx = planePoint[j].x;
				}
			}
		}
		if (ttmaxy != g_middlePoint.y)//添加新点
		{
			GPS_POINT_Data2[GPS_POINT_Index1].x = ttmaxx;
			GPS_POINT_Data2[GPS_POINT_Index1].y = ttmaxy;
			GPS_POINT_Index1++;
			k++;
		}
	}
	//去掉3点间，中间最低点
	if (k<2)return;
	for (i = 2; i<k; i++)
	{
		if (GPS_POINT_Data2[GPS_POINT_Index1 - i].y<GPS_POINT_Data2[GPS_POINT_Index1 - i - 1].y && GPS_POINT_Data2[GPS_POINT_Index1 - i].y<GPS_POINT_Data2[GPS_POINT_Index1 - i + 1].y)
			GPS_POINT_Data2[GPS_POINT_Index1 - i].y = GPS_POINT_Data2[GPS_POINT_Index1 - i + 1].y;
	}
	TopMiny = GPS_POINT_Data2[GPS_POINT_Index1 - 1].y;
	for (i = 1; i<k; i++)//取出上边线，最小的Y值
	{
		if (TopMiny>GPS_POINT_Data2[GPS_POINT_Index1 - i].y)TopMiny = GPS_POINT_Data2[GPS_POINT_Index1 - i].y;
	}
}

//////----求最右边连续点-----/////////
static double RightMinx;
static void CalRightPiont(u32 count)
{
	double ttmaxy = 0;
	double ttmaxx = 0;
	u32 i, j, k;
	double dy;
	dy = LengMaxy / count;
	k = 0;
	for (i = 0; i<count; i++)//分割后循环
	{
		ttmaxx = g_middlePoint.x;
		for (j = 0; j <planePointIndex - 2; j++)//循环所有线条
		{
			if (planePoint[j].y <= (g_tmaxy - i*dy) && planePoint[j].y >= (g_tmaxy - (i + 1)*dy))
			{
				if (ttmaxx<planePoint[j].x)
				{
					ttmaxy = planePoint[j].y;
					ttmaxx = planePoint[j].x;
				}
			}
		}
		if (ttmaxx != g_middlePoint.x)
		{
			GPS_POINT_Data2[GPS_POINT_Index1].x = ttmaxx;
			GPS_POINT_Data2[GPS_POINT_Index1].y = ttmaxy;
			GPS_POINT_Index1++;
			k++;
		}
	}

	//去掉3点间，中间最左点
	if (k<2)return;
	for (i = 2; i<k; i++)
	{
		if (GPS_POINT_Data2[GPS_POINT_Index1 - i].x<GPS_POINT_Data2[GPS_POINT_Index1 - i - 1].x
			&&GPS_POINT_Data2[GPS_POINT_Index1 - i].x<GPS_POINT_Data2[GPS_POINT_Index1 - i + 1].x)
			GPS_POINT_Data2[GPS_POINT_Index1 - i].x = GPS_POINT_Data2[GPS_POINT_Index1 - i + 1].x;
	}

	RightMinx = GPS_POINT_Data2[GPS_POINT_Index1 - 1].x;
	for (i = 1; i<k; i++)
	{
		if (RightMinx>GPS_POINT_Data2[GPS_POINT_Index1 - i].x)RightMinx = GPS_POINT_Data2[GPS_POINT_Index1 - i].x;
	}

}

//////----求最低边连续点-----/////////
static void CalBottomPiont(u32 count)
{
	double tminx, tminy;
	u32 i, j, k;
	double dx;
	k = 0;
	tminx = tminy = 100000;//100km
	dx = LengMaxx / count;
	for (i = 0; i<count; i++)//分割后循环
	{
		tminy = g_middlePoint.y;
		for (j = 0; j <planePointIndex - 2; j++)//循环所有线条
		{
			if (planePoint[j].x <= (g_tmaxx - i*dx) && planePoint[j].x >= (g_tmaxx - (i + 1)*dx))
			{
				if (tminy>planePoint[j].y)
				{
					tminy = planePoint[j].y;
					tminx = planePoint[j].x;
				}
			}
		}
		if (tminy != g_middlePoint.y)
		{
			GPS_POINT_Data2[GPS_POINT_Index1].x = tminx;
			GPS_POINT_Data2[GPS_POINT_Index1].y = tminy;
			GPS_POINT_Index1++;
			k++;
		}
	}
	//去掉3点间，中间最高点
	if (k<2)return;
	for (i = 2; i<k; i++)
	{
		if (GPS_POINT_Data2[GPS_POINT_Index1 - i].y>GPS_POINT_Data2[GPS_POINT_Index1 - i - 1].y &&GPS_POINT_Data2[GPS_POINT_Index1 - i].y>GPS_POINT_Data2[GPS_POINT_Index1 - i + 1].y)
			GPS_POINT_Data2[GPS_POINT_Index1 - i].y = GPS_POINT_Data2[GPS_POINT_Index1 - i + 1].y;
	}

	BottomMaxy = GPS_POINT_Data2[GPS_POINT_Index1 - 1].y;
	for (i = 1; i<k; i++)
	{
		if (BottomMaxy<GPS_POINT_Data2[GPS_POINT_Index1 - i].y)
			BottomMaxy = GPS_POINT_Data2[GPS_POINT_Index1 - i].y;
	}

}

//////----求最左边连续点-----/////////
static void CalLeftPiont(u32 count)
{
	double tminx, tminy;
	u32 i, j, k;
	double dy;
	k = 0;
	tminx = tminy = 100000;//100km
	dy = LengMaxy / count;
	for (i = 0; i<count; i++)//分割后循环
	{
		tminx = g_middlePoint.x;
		for (j = 0; j <planePointIndex - 2; j++)//循环所有线条
		{
			if (planePoint[j].y >= (g_tminy + i*dy) && planePoint[j].y <= (g_tminy + (i + 1)*dy))
			{

				if (tminx>planePoint[j].x)
				{
					tminy = planePoint[j].y;
					tminx = planePoint[j].x;
				}
			}
		}
		if (tminx != g_middlePoint.x)
		{
			GPS_POINT_Data2[GPS_POINT_Index1].x = tminx;
			GPS_POINT_Data2[GPS_POINT_Index1].y = tminy;
			GPS_POINT_Index1++;
			k++;
		}
	}
	if (k<2)return;
	//去掉3点间，中间最右点
	for (i = 2; i<k; i++)
	{
		if (GPS_POINT_Data2[GPS_POINT_Index1 - i].x>GPS_POINT_Data2[GPS_POINT_Index1 - i - 1].x &&GPS_POINT_Data2[GPS_POINT_Index1 - i].x>GPS_POINT_Data2[GPS_POINT_Index1 - i + 1].x)
			GPS_POINT_Data2[GPS_POINT_Index1 - i].x = GPS_POINT_Data2[GPS_POINT_Index1 - i + 1].x;
	}
}


//得到因GPS天线安装位置偏差带来的面积误差
/*double GetOffsetAreaForAntennaPosition(void)
{
u16 i=0;
double x1;
double x2;
double y1;
double y2;
double area=0;
double QuYangLength =0;

for(i=0;i<GPS_POINT_Index1;i++)
{
x1=GPS_POINT_Data2[i].x;
x2=GPS_POINT_Data2[i+1].x;
y1=GPS_POINT_Data2[i].y;
y2=GPS_POINT_Data2[i+1].y;
QuYangLength+=sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1));
}
area =SysInfor.WORKING_WIDTH*QuYangLength/200;
//area =g_workingWidth*QuYangLength/200;
return area;
}*/
double GetOffsetAreaForAntennaPosition(void)
{
	unsigned short i = 0;
	double x1;
	double x2;
	double y1;
	double y2;
	double area = 0;
	double QuYangLength = 0;

	for (i = 0; i<GPS_POINT_Index1 - 1; i++)
	{
		x1 = GPS_POINT_Data2[i].x;
		x2 = GPS_POINT_Data2[i + 1].x;
		y1 = GPS_POINT_Data2[i].y;
		y2 = GPS_POINT_Data2[i + 1].y;
		QuYangLength += sqrt((x2 - x1)*(x2 - x1) + (y2 - y1)*(y2 - y1));
	}
	area = SysInfor.WORKING_WIDTH * QuYangLength / 200;
	LOGE("gps******补偿面积:%lf", area / 666.7);
	return area;
}

//////////----取边界点后求面积---///////////
static double CaliAreaXuanDian(void)
{
	double iArea = 0;
	u16 count = 6;//分步数
	u16 slen = SysInfor.WORKING_WIDTH / 100;
	u16 t;
	if (planePointIndex<20)return 0;
	/////////----求最高连续点-----/////////////////////
	memset(GPS_POINT_Data2, 0, sizeof(GPS_POINT_Data2));
	GPS_POINT_Index1 = 0;
	if (count<LengMaxx / slen)
		t = (u32)(LengMaxx / slen);
	else
		t = count;
	CalTopPiont(t);
	/////////----求最右边连续点-----/////////////////////
	if (count<LengMaxy / slen)t = (int)(LengMaxy / slen); else t = count;
	CalRightPiont(t);
	/////////----求最低连续点-----/////////////////////
	if (count<LengMaxx / slen)t = (int)(LengMaxx / slen); else t = count;
	CalBottomPiont(t);
	/////////----求最左边连续点-----/////////////////////
	if (count<LengMaxy / slen)t = (int)(LengMaxy / slen); else t = count;
	CalLeftPiont(t);
	iArea = CaliArea(GPS_POINT_Data2, GPS_POINT_Index1);//求面积

	LOGE("gps******轮廓面积:%lf", iArea / 666.7);
	iArea += GetOffsetAreaForAntennaPosition();

	CaliAreaFlag = 1;
	return (iArea / 666.67);

}


